package com.yunwushanhe.document.controller;


import com.yunwushanhe.document.entity.Users;
import com.yunwushanhe.document.utils.FileUtils;
import com.yunwushanhe.document.utils.MailUtils;
import com.yunwushanhe.document.service.impl.UsersServiceImpl;
import com.yunwushanhe.document.utils.Unify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 云雾山河
 * @since 2022-10-09
 */
@Slf4j
@Controller
@RequestMapping("/document/users")
public class UsersController {
    @Autowired
    UsersServiceImpl usersService;
    @Autowired
    MailUtils mailUtils;
    @Autowired
    FileUtils fileUtils;
    @Autowired
    Unify unify;

    private String code = "$^%^%767371%%^%^$##";
    //这里有问问题，最好不要再Controller,Service层里面定义变量，因为涉及到单列模式的使用，这种变量在并发的时候会被不断覆盖，最终导致出问题。
    // 详细解释网址 https://www.cnblogs.com/zhangshitong/p/9166727.html
    private String regx = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";

    /**
     * 用于登录的功能
     * @param userNumber
     * @param password
     * @param model
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("userNumber") String userNumber,
                        @RequestParam("password") String password,
                        Model model, HttpSession session)
    {
        Users user = usersService.getUserByNumberAndPassword(userNumber, password);
        if(user == null){
            model.addAttribute("msg","账号或者密码错误！");
            return "login";
        } else {
            session.setAttribute("loginUser",user.getUsername());
            model.addAttribute("msg",null);
            return "main";
        }
    }

    /**
     * 注册
     * @param user
     * @param model
     * @return
     */
    @PostMapping
    public String register(Users user,Model model){
        boolean emptyFlag = !user.getUsername().isEmpty();
        boolean spaceFlag = !user.getUsername().contains(" ");
        //必须是包含大小写字母、数字、特殊符号的6到18位组合
        boolean regFlag = user.getPassword().matches("^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])^.{6,18}$");
        //是否符合邮箱格式
        boolean numberFlag = user.getUserNumber().matches("^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$");

        Users users = usersService.getUserNumber(user.getUserNumber());
        if(this.code.equals(user.getCode()) && !user.getCode().isEmpty()
                && users == null && !user.getUserNumber().isEmpty()
                && emptyFlag && spaceFlag && regFlag && numberFlag){
            //注册成功
            usersService.insertUser(user);
            this.code = "$^%^%767371%%^%^$##";
            model.addAttribute("registerMessageCode",null);
            model.addAttribute("registerMessageNumber",null);
            model.addAttribute("registerMessageNumberFormat",null);
            model.addAttribute("registerMessageName",null);
            model.addAttribute("registerMessagePassword",null);
            fileUtils.createUserTopFolder(user.getUserNumber());//创建用户对应的文件夹
            return "login";
        } else {
            if(!this.code.equals(user.getCode()) || user.getCode().isEmpty()){
                model.addAttribute("registerMessageCode","验证码错误，请从新输入！");
            }
            if(users != null || user.getUserNumber().isEmpty()){
                model.addAttribute("registerMessageNumber","该账号已被注册过（不能为空！），请重新输入！");
            }
            if(!numberFlag){
                model.addAttribute("registerMessageNumberFormat","账号必须是邮箱地址，请输入正确的邮箱地址格式！");
            }
            if(!emptyFlag || !spaceFlag){//有其一就可以给出提示
                model.addAttribute("registerMessageName","用户名不能为空或者包含字符串，请重新输入！");
            }
            if(!regFlag){
                model.addAttribute("registerMessagePassword","密码必须是包含大小写字母、数字的6到18位组合，请重新输入！");
            }
            return "register";
        }
    }

    @ResponseBody
    @PostMapping("/send/{userNumber}")
    public Unify sendEmail(@PathVariable("userNumber")String userNumber,Model model){
        Users users = usersService.getUserNumber(userNumber);
        boolean userNumberFlag = userNumber.matches(this.regx);
        if(users == null && !userNumber.isEmpty() && userNumberFlag){
            this.code = mailUtils.createCode();
            mailUtils.sendSimpleEmail(userNumber,"文件管理系统注册验证码来辣！","云雾山河给你发验证码来啦！\n"+code+"\n该验证密码打死也不要发给其他人哦！\n有效期：下一次点击发送验证码之前都有效！");
            unify.setFlag(true);
//            model.addAttribute("messageNumberFormat01",null);
            return unify;
        } else {
            unify.setMessage("该账号已被注册过（不能为空！），请重新输入！");
            if(!userNumberFlag){
                unify.setMessage("账号必须是邮箱地址，请输入正确的邮箱地址格式！");
//                model.addAttribute("messageNumberFormat01","账号必须是邮箱地址，请输入正确的邮箱地址格式！");
            }
            unify.setFlag(false);
            return unify;
        }
    }

    /**
     * 修改密码
     * @param user
     * @param model
     * @return
     */
    @PostMapping("/update")
    public String updatePwd(Users user,Model model){
        Users oldUser = usersService.getUsers();
        model.addAttribute("oldUser",oldUser);
        boolean flagName = oldUser.getUsername().equals(user.getUsername());
        boolean flagNumber = oldUser.getUserNumber().equals(user.getUserNumber());
        boolean flagPassword = oldUser.getPassword().equals(user.getPassword());
        boolean flagSure = user.getNewPassword().equals(user.getSurePassword());
        //必须是包含大小写字母、数字、特殊符号的6到18位组合
        boolean passwordFlag = user.getNewPassword().matches("^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])^.{6,18}$");

        if(flagName && flagNumber && flagPassword && flagSure && passwordFlag){
            user.setPassword(user.getNewPassword());
            usersService.updateUser(user);
            model.addAttribute("changeMessageName",null);
            model.addAttribute("changeMessageNumber",null);
            model.addAttribute("changeMessagePassword",null);
            model.addAttribute("changeMessageSure",null);
            model.addAttribute("changeMessagePasswordFormat",null);
            this.code = "$^%^%767371%%^%^$##";
            return "login";
        } else {
            if(!flagName){
                model.addAttribute("changeMessageName","用昵称不能修改！");
            }
            if(!flagNumber){
                model.addAttribute("changeMessageNumber","账号不能修改！");
            }
            if(!flagPassword){
                model.addAttribute("changeMessagePassword","原有密码输入错误！");
            }
            if(!flagSure){
                model.addAttribute("changeMessageSure","两次新密码输入不一致，请检查后重新输入！");
            }
            if(!passwordFlag){
                model.addAttribute("changeMessagePasswordFormat","密码必须是包含大小写字母、数字的6到18位组合，请重新输入！");
            }
            return "change";
        }
    }

    /**
     * 前往修改密码页面
     * @param model
     * @return
     */
    @PostMapping("/change")
    public String goChange(Model model){
        Users oldUser = usersService.getUsers();
        model.addAttribute("oldUser",oldUser);
        return "change";
    }

    /**
     * 重置密码
     * @param user
     * @param model
     * @return
     */
    @PostMapping("/retrieve")
    public String goRetrieve(Users user,Model model){
        Users users = usersService.getUserNumber(user.getUserNumber());
        boolean flagCode = this.code.equals(user.getCode());
        boolean flagSure = user.getNewPassword().equals(user.getSurePassword());
        //必须是包含大小写字母、数字、特殊符号的6到18位组合
        boolean passwordFlag = user.getNewPassword().matches("^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])^.{6,18}$");
        //是否符合邮箱格式
        boolean numberFlag = user.getUserNumber().matches("^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$");

        if(flagSure && users!=null && flagCode && passwordFlag && numberFlag){
            user.setPassword(user.getNewPassword());
            usersService.retrieveUser(user);
            model.addAttribute("retrieveMessageCode",null);
            model.addAttribute("retrieveMessageNumber",null);
            model.addAttribute("retrieveMessageSure",null);
            model.addAttribute("retrieveMessageNumberFormat",null);
            model.addAttribute("retrieveMessagePassword",null);
            this.code = "$^%^%767371%%^%^$##";
            return "login";
        } else {
            if(users==null){
                model.addAttribute("retrieveMessageNumber","该账号未被注册，不能被重置密码（不能发送验证码）！");
            }
            if(!flagCode){
                model.addAttribute("retrieveMessageCode","验证码错误，请从新输入！");
            }
            if(!flagSure){
                model.addAttribute("retrieveMessageSure","两次新密码输入不一致，请检查后重新输入！");
            }
            if(!numberFlag){
                model.addAttribute("retrieveMessageNumberFormat","账号必须是邮箱地址，请输入正确的邮箱地址格式！");
            }
            if(!passwordFlag){
                model.addAttribute("retrieveMessagePassword","密码必须是包含大小写字母、数字的6到18位组合，请重新输入！");
            }
            return "retrieve";
        }
    }

    /**
     * 注册账号时需要发送的验证码
     * @param userNumber
     * @return
     */
    @ResponseBody
    @PostMapping("/send2/{userNumber}")
    public Unify send2Email(@PathVariable("userNumber")String userNumber,Model model){
        boolean userNumberFlag = userNumber.matches(this.regx);
        Users users = usersService.getUserNumber(userNumber);
        if(users != null && !userNumber.isEmpty() && userNumberFlag){
            this.code = mailUtils.createCode();
            mailUtils.sendSimpleEmail(userNumber,"文件管理系统注册验证码来辣！","云雾山河给你发验证码来啦！\n"+code+"\n该验证密码打死也不要发给其他人哦！\n有效期：下一次点击发送验证码之前都有效！");
            unify.setFlag(true);
            System.out.println("1111111111111");
//            model.addAttribute("messageNumberFormat02",null);
            return unify;
        } else {
            unify.setMessage("该账号未被注册过（不能为空！），请重新输入！");
            if(!userNumberFlag){
                unify.setMessage("账号必须是邮箱地址，请输入正确的邮箱地址格式！");
//                model.addAttribute("messageNumberFormat02","账号必须是邮箱地址，请输入正确的邮箱地址格式！");
            }
            unify.setFlag(false);
            System.out.println("2222222222222222222222");
            return unify;
        }
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @PostMapping("/exit")
    public String exit(HttpSession session){
        session.invalidate();
        return "login";
    }

    /**
     * 跳转到首页
     * @return
     */
    @PostMapping("/in")
    public String index(){
        return "redirect:/"; //重定向这里必定要传入已经定义好的路径，而非一个页面名
    }

    /**
     * 跳转到主页
     * @return
     */
    @GetMapping("/remain")
    public String remain(){
        return "main";
    }

    /**
     * 跳转到文件功能页面
     * @return
     */
    @GetMapping("/file")
    public String goFileOperation(){
        System.out.println("fileFunction");
        return "fileFunction";
    }

    /**
     * 跳转到成功页面
     * @return
     */
    @PostMapping("/success")
    public String success(){
        System.out.println("success");
        return "success";
    }

    /**
     * 把userNumber传递给前端，然后前端再传递给fileController
     * @return
     */
    @ResponseBody
    @GetMapping("/getUserNumber")
    public Unify getUserNumber(){
        unify.setData(usersService.getUsers().getUserNumber());
        log.info("=============={}=============",usersService.getUsers().getUserNumber());
        return unify;
    }
}

